// pages/daka/daka.js
var wxRequest = require('../../utils/request.js');
var amapFile = require('../../libs/amap-wx.js'); 
var util = require('../../utils/util.js');
var app = getApp()
var markersData = {
  latitude: '',//纬度
  longitude: '',//经度
  key: "63cf118caca0fbf423c918f67069d820",
};

var tianqi = [
  '多云',
  '雷雨',
  '晴天',
  '沙尘',
  '雾霾',
  '小雨',
  '下雪',
  '阴天',
  '中雨',
  '雨雪',
  '阵雨',
  '扬沙'
];

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageBackgroundColor: 'bg-olive',
    feel: '还行',
    picker: tianqi,
    tqIndex: null,
    // weather:'未知',
    date:'2019-12-31',
    isLoading:'',
    context:'', 
    PageCur: '',
    backgroundColor: 'olive',
    imgList: [],
    imageList:[],
    adUrl: wxRequest.host + '/uploads/tupian/olive.jpg',
  },
  
  ChooseImage() {
    console.log(wxRequest.host)
    var that = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res);
        //上传到后台
        var tempFilePaths = res.tempFilePaths;
        // console.log(tempFilePaths)
        wx.uploadFile({
          url: wxRequest.host + '/api/common/upload', //接口
          filePath: tempFilePaths[0],
          name: 'file',
          success: function (res) {
            console.log(res)
            // var images = res.data;
            var jsonObj = JSON.parse(res.data);
            var imageUrl = wxRequest.host + jsonObj.data.url;
            var imageList = new Array();
            var imgArr = new Array();
            imageList.push(imageUrl);
            imgArr.push(jsonObj.data);
            // console.log(jsonObj);
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(imageList),
                imageList: that.data.imageList.concat(imgArr)
              })
            } else {
              that.setData({
                imgList: imageList,
                imageList: imgArr
              })
            }
            
            
          },
          fail: function (error) {
            console.log(error);
          }
        });
        // if (this.data.imgList.length != 0) {
        //   this.setData({
        //     imgList: this.data.imgList.concat(res.tempFilePaths)
        //   })
        // } else {
        //   this.setData({
        //     imgList: res.tempFilePaths
        //   })
        // }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },


  NavChange(e) {
    wx.redirectTo({
      url: e.currentTarget.dataset.cur,
    })
  },

  //选择天气
  PickerChange(e) {
    this.setData({
      tqIndex: e.detail.value
    })
  },

  getUserInfo(e){
    console.log(e);
    var data = {
      context: this.data.context,
      weather: tianqi[this.data.tqIndex],
      date_time: this.data.date,
      bg_color: this.data.pageBackgroundColor,
      color: this.data.backgroundColor,
      feel:this.data.feel,
      images: this.data.imageList,
      userInfo:e.detail.userInfo,
    };

    this.setData({
      isLoading: 'cuIcon-icloading',
    })
    
    var submitUrl = '/api/xqdaka/insertdata?wxToken=' + wx.getStorageSync('openid');
    wxRequest.postRequest(submitUrl, data, this.dakaInsertSuccess);

    // console.log(data);
    // console.log(this.data.date);
    // console.log(this.data.context);
    // console.log(tianqi[this.data.tqIndex]);
  },

  dakaInsertSuccess: function (res) {
    wx.showToast({
      title: res.msg,
      icon: 'none',
      duration: 2000
    })

    if(res.code == 0){
      this.setData({
        isLoading: '',
      })
    }

    if(res.code == 1){
      wx.switchTab({
        url: "../dateTime/dateTime",
        success(res) {
          let page = getCurrentPages().pop();
          if (page == undefined || page == null) {
            return
          }
          page.onLoad();
        }
      })
    }

  },

  //点击更换颜色
  btnclick: function (e) {
    var color = e.target.dataset.color;
    var feel = e.target.dataset.feel;
    this.setData({
      pageBackgroundColor: 'bg-' + color,
      feel:feel,
      backgroundColor: color,
      adUrl: wxRequest.host + '/uploads/tupian/' + color + '.jpg',
    })
  },

  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  textareaAInput(e){
    this.setData({
      context:e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        // console.log(res);
        var  latitude = res.latitude
        var  longitude = res.longitude
        that.loadCity(latitude, longitude);
      }
    });

    var time = util.formatTimeByDay(new Date());

    this.setData({
      date:time
    })

    var pages = getCurrentPages()
    var currentPage = pages[pages.length - 1]
    this.setData({
      PageCur: currentPage.route
    })

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    // //获取当前页面的数据
    // var indexUrl = '/api/xqdaka/index';
    // wxRequest.getRequest(indexUrl, this.indexSuccess);
  },


  indexSuccess: function (res) {
    this.setData({
      adUrl:res.data.imageUrl,
    })
  },



  //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置，天气情况等信息
  loadCity: function (latitude, longitude) {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({ key: markersData.key });
    // myAmapFun.getRegeo({
    //   location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
    //   success: function (data) {
    //     console.log(data);
    //   },
    //   fail: function (info) { }
    // });

    myAmapFun.getWeather({
      success: function (data) {
        console.log(data);
        that.getIndex(data.weather.data)
        // that.setData({
        //   weather: '11'
        // })
        // console.log(data);
        //成功回调
      },
      fail: function (info) {
        //失败回调
        console.log(info)
      }
    })
  },

  //获取数组的下标
  getIndex: function (weather){
    // var that = this;
    // console.log(weather)
    // console.log(tianqi);
    if (weather == '阴' || weather == '晴'){
      weather = weather + "天";
    }
    var index = null;
    for (var i = 0; i < tianqi.length; ++i) {
      if (tianqi[i] == weather){
        index = i;
        break;
      }
    }
    this.setData({
      tqIndex: index 
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // var getDakaInfoUrl = '/api/xqdaka';
    // wxRequest.getRequest(getDakaInfoUrl, this.dakaIndexSuccess);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})